/**
 * cart.js Created by Administrator on 2017/9/16.
 */

import Vue from 'vue'
import Vuex from 'vuex'
import * as types from './mutationNames'

Vue.use(Vuex)

//定义state
const state = {
    added: []   //形状：[{id, count}, ...]
}

//定义getters -- 相当于Store的计算属性
const getters = {
}

//Mutations
//作用：同步调用 store.commit 方法，更改 Vuex 的 store 中的状态的唯一方法
const mutations = {
    [types.ADD_TO_CART]: function (state, id) {
        let item = state.added.find(item=>item.id === id)
        if(item === undefined){
            state.added.push({id, count: 1})
        } else {
            item.count++
        }
    },
    [types.REMOVE_FROM_CART]: function (state, id) {
        let item = state.added.find(item=>item.id === id)
        if(item) {
            if(item.count > 1){
                item.count--;
            }else{
                state.added = state.added.filter(item=>item.id !== id)
            }
        }
    },
    //payload: {product, count, oldcount}
    [types.UPDATE_PRODUCT_COUNT]: function (state, payload) {
        console.log('cart.js UPDATE_PRODUCT_COUNT: ')
        console.log(payload)
        if(payload.count <= 0) return

        let item = state.added.find(item=>item.id === payload.product.id)
        if(item) {
            item.count = payload.count;
        }
    },
    [types.CLEART_CART]: function (state) {
        state.added = []
    }
}

//Actions
//作用：1.提交的是 mutation，而不是直接变更状态
//     2.可以包含任意异步操作
const actions = {
}

//导出Store
export default {
    state,
    getters,
    mutations,
    actions
};